<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown } from '@element-plus/icons-vue';
import { useI18n } from "vue-i18n";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
// 引入组件
import AddFirmware from './component/add.vue';
import EditFirmware from './component/edit.vue';
import { getFirmwareListApi, deleteFirmwareApi } from "@/api/products/firmware";
import { getProductOptionsApi } from "@/api/products/product";
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";

const { t } = useI18n();

//一定要和服务端的权限名称一样
defineOptions({
  name: "firmware-manage"
});

// 固件列表数据
const firmwareList = ref<any[]>([]);
const total = ref(0);
// 产品选项
const productOptions = ref([]);
const pageSizeOps = ref(pageSizeOptions)

const searchParams = ref({
  page: 1,
  pageSize: 10,
  name: "",
  version: "",
  productId:"",
  timeRange:[]
});

// 搜索字段配置 - 修改为小驼峰命名
const searchFields = ref([
  { prop: "name", name: t('products.firmwarePage.firmwareName'), type: "input", placeholder: t('products.firmwarePage.searchFirmwareName') },
  { prop: "version", name: t('products.firmwarePage.firmwareVersion'), type: "input", placeholder: t('products.firmwarePage.searchFirmwareVersion') },
  {
    prop: "productId",
    name: t('products.firmwarePage.productName'),
    type: "select",
    formOptions: productOptions,
  },
  { prop: 'timeRange', name: t("buttons.timeRange"), type: 'datetimeRange', clearable: true, isHidden: false, },
]);

// 加载产品选项
const loadProductOptions = async () => {
  const response = await getProductOptionsApi();
  if (response.code === 0) {
    productOptions.value = response.data.options;
  }
};

// 加载固件列表
const loadFirmwareList = async () => {
  try {
    //@ts-ignore
    const response = await getFirmwareListApi({
      ...searchParams.value
    });

    if (response.code === 0) {
      firmwareList.value = response.data.list || [];
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || '获取固件列表失败');
    }
  } catch (error) {
    total.value = 0
    ElMessage.error('获取固件列表失败');
    console.error('Failed to load firmware list:', error);
  }
};

// 命令处理函数
const handleCommand = async (command: string, firmwareId: number) => {
  if (command === 'delete') {
    await handleDelete(firmwareId);
  }
};

// 删除固件
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t('products.firmwarePage.confirmDelete'),
      t('products.firmwarePage.confirmTitle'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const response = await deleteFirmwareApi(id);
    if (response.code === 0) {
      ElMessage.success(t('products.firmwarePage.deleteFirmwareSuccess'));
      await loadFirmwareList();
    } else {
      ElMessage.error(response.msg || t('products.firmwarePage.deleteFirmwareFail'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('products.firmwarePage.deleteFirmwareFail'));
      console.error('Failed to delete firmware:', error);
    }
  }
};

// 初始加载
onMounted(() => {
  loadProductOptions();
  loadFirmwareList();
});


// 搜索处理
const handleSearch = (e: any) => {
  // 重置页码
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  searchParams.value.page = 1;
  // 加载数据
  loadFirmwareList();
};

// 重置搜索
const handleReset = () => {
  console.log("Reset search");
  // 重置页码
  searchParams.value.page = 1;
  // 加载数据
  loadFirmwareList();
};

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  console.log(pageSize);
  searchParams.value.pageSize = pageSize;
  loadFirmwareList();
};
const handlePaginationPageChange = (page: number) => {
  console.log(page);
  searchParams.value.page = page;
  loadFirmwareList();
};

// 格式化存放位置
const formatStorageLocation = (location: number) => {
  return location === 0 ? t('products.firmwarePage.local') : t('products.firmwarePage.other');
};

// 控制弹框显示
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentFirmware = ref<any>(null);

// 打开新增弹框
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 打开编辑弹框
const openEditDialog = (firmware: any) => {
  currentFirmware.value = { ...firmware };
  editDialogVisible.value = true;
};

// 关闭弹框后的回调
const handleClose = () => {
  // 可以在这里添加一些清理逻辑
};

// 刷新列表
const refreshList = () => {
  loadFirmwareList();
};
</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :initial-values="searchParams"
          :fields="searchFields"
          :maxVisibleFields="3"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <!--按钮区-->
    <div class="button-area">
      <el-button
        type="primary"
        icon="Plus"
        @click="openAddDialog"
      >
        {{ t('products.firmwarePage.addFirmware') }}
      </el-button>
    </div>

    <!-- 卡片列表 -->
    <div class="firmware-list-container">
      <div v-if="firmwareList.length === 0" class="empty-state">
        <el-empty :description="t('products.firmwarePage.noFirmwareData')" />
      </div>
      <div v-else class="firmware-grid">
        <el-card
          v-for="firmware in firmwareList"
          :key="firmware.id"
          class="firmware-card"
          :body-style="{ padding: '16px' }"
        >
          <div class="firmware-info">
            <div class="firmware-image">
              <img
                :src="firmware.image || '/images/default-firmware.png'"
                :alt="firmware.name"
                class="firmware-img"
              />
            </div>
            <div class="firmware-details">
              <h3 class="firmware-name">{{ firmware.name }}</h3>
              <div class="firmware-meta">
                <div class="meta-item">
                  <span class="meta-label">{{ t('products.firmwarePage.firmwareVersion') }}:</span>
                  <span class="meta-value">{{ firmware.version }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ t('products.firmwarePage.productName') }}:</span>
                  <span class="meta-value">{{ firmware.productName }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ t('products.firmwarePage.firmwarePart') }}:</span>
                  <span class="meta-value">{{ firmware.part || '-' }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ t('products.firmwarePage.storageLocation') }}:</span>
                  <span class="meta-value">{{ formatStorageLocation(firmware.whereAt) }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">{{ t('products.firmwarePage.createdAt') }}:</span>
                  <span class="meta-value">{{ firmware.createdAt }}</span>
                </div>
              </div>
              <div class="firmware-description">{{ firmware.remark }}</div>
            </div>
          </div>
          <div class="firmware-actions">
                <el-dropdown @command="(command) => handleCommand(command, firmware.id)">
                  <el-button size="small" plain  type="info">
                    {{ t('products.firmwarePage.manage') }} <el-icon class="el-icon--right"><arrow-down /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>

                      <el-dropdown-item @click="openEditDialog(firmware)">{{ t('buttons.edit') }}</el-dropdown-item>

                      <el-dropdown-item command="delete" type="danger"  style="margin-top: 10px; color:red">{{ t('buttons.delete') }}</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="pageSizeOps"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePaginationSizeChange"
          @current-change="handlePaginationPageChange"
        />
      </div>
    </div>

    <!-- 新增弹框 -->
    <AddFirmware
      v-model:visible="addDialogVisible"
      @close="handleClose"
      @success="refreshList"
    />

    <!-- 编辑弹框 -->
    <EditFirmware
      v-model:visible="editDialogVisible"
      :firmware="currentFirmware"
      @close="handleClose"
      @success="refreshList"
    />
  </el-card>
</template>

<style scoped lang="scss">
.firmware-list-container {
  padding: 20px 0;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.firmware-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.firmware-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.firmware-info {
  display: flex;
  margin-bottom: 16px;
  flex: 1;
}

.firmware-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  flex-shrink: 0;
}

.firmware-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.firmware-details {
  flex: 1;
  min-width: 0;
}

.firmware-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.firmware-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 16px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.meta-label {
  color: #606266;
  margin-right: 4px;
}

.meta-value {
  color: #303133;
}

.firmware-description {
  font-size: 12px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.firmware-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
